package com.project.servlet;

import com.github.pagehelper.PageInfo;
import com.project.bean.ManBean;
import com.project.service.IManService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@Controller
public class FindAllServlet extends HttpServlet {
    @Autowired
    private IManService service;

    @Override
    public void init() throws ServletException {
        System.out.println("------------执行findAll的init");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        //得到页码
        String pg = req.getParameter("pageNO");
        int pageNO = 1;
        if(pg != null){
            pageNO = Integer.parseInt(pg);
        }

        //调用业务方法得到结果
        PageInfo<ManBean> pageInfo = service.findAll(pageNO);
        //当前页显示的数据
        List<ManBean> list = pageInfo.getList();
        //总页数
        int pages = pageInfo.getPages();

        String str = "<table border='1' width='60%' cellspacing='0'>";
        str += "<thead><tr><th>姓名</th><th>生日</th></tr></thead>";
        str += "<tbody>";
            for(ManBean man : list){
               str += "<tr><td>"+man.getName()+"</td><td>"+man.getBirthday()+"</td></tr>";
            }
        str += "</tbody></table>";

        for(int i=1;i<=pages;i++){
            str += "<a style='margin-left:10px;' href='/findAll?pageNO="+i+"'>"+i+"</a>";
        }

        resp.getWriter().println(str);
    }
}
